//
//  ZTOrderViewController.m
//  FD
//
//  Created by Yasin on 2018/10/15.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  自提订单

#import "ZTOrderViewController.h"
//Cell
#import "ZTOrderTableViewCell.h" //xib
#import "FDNowDataView.h" //没有数据
#import "XLAlertView.h" //弹框2019-1-22

//controller
#import "ZTOrderDetailViewController.h"
#import "EvaluateController.h" //1-22评价
#import "WSPayUrlViewController.h"//1-22网页支付vc
#import "WSZaiLaiYiDanViewController.h" //1-22再来一单
#import "ZTOrderViewController.h" //1-22 订单详情

#import <MJRefresh.h>

//model
#import "ZTOrderModel.h"

//tool
#import "FDPaytypeAlertTool.h" //2019-2-13



@interface ZTOrderViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tv1;
/**数据源*/
@property (nonatomic,  strong) NSMutableArray *dataArr;
/**没有数据view 默认隐藏*/
@property (nonatomic, strong) FDNowDataView *nodateView;
/**1-23全局菊花方式盖住按钮防止重复点击*/
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation ZTOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //布局
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self loadZTData];
    [self addTableViewRefresh]; //刷新加载功能
}

- (void)setupUI {
    //使用MJRefresh 修改contentInset属性会导致莫名其妙的问题。
    CGFloat tv1y = FD_NavH + 35; //上面的标题的高度是35
    CGFloat tv1h = SCREEN_HEIGHT - tv1y - Height_TabBar - FD_TabbarSafeBottomMargin;
    self.tv1.frame = CGRectMake(0, tv1y, SCREEN_WIDTH, tv1h);
    self.tv1.tableFooterView = [UIView new];
    [self.view addSubview:self.tv1];
    
//    self.tv1.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.nodateView];
    self.nodateView.hidden = YES; //默认隐藏
    [self.nodateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, 30));
        make.centerY.equalTo(self.view.mas_centerY);
    }];
}

//添加刷新加载
- (void)addTableViewRefresh {
    FDRefreshHader *refreshHeader = [FDRefreshHader headerWithRefreshingTarget:self refreshingAction:@selector(loadZTData)];
    self.tv1.mj_header = refreshHeader;
    [self.tv1.mj_header beginRefreshing];
}


#pragma mark - getter
- (UITableView *)tv1 {
    if (!_tv1) {
        _tv1 = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tv1.delegate = self;
        _tv1.dataSource = self;
        
        //注册cell
        [_tv1 registerNib:[UINib nibWithNibName:@"ZTOrderTableViewCell" bundle:nil] forCellReuseIdentifier:@"ZTOrderTableViewCell"];
        _tv1.showsVerticalScrollIndicator = NO;
        
        //取消线
        _tv1.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _tv1;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (FDNowDataView *)nodateView {
    if (!_nodateView) {
        _nodateView = [[FDNowDataView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
//        _nodateView.hidden = YES; //默认隐藏
    }
    return _nodateView;
}

#pragma mark - 代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZTOrderTableViewCell *ztCell = [tableView dequeueReusableCellWithIdentifier:@"ZTOrderTableViewCell"];
    ZTOrderModel *model = self.dataArr[indexPath.row];
    ztCell.model = model;
    
    //如果触发了这个按钮那就是再来一单
    ztCell.clickLeftBtnBlcok = ^{
        [self ztHandleOnceOrder:model.orderId];
    };

    ztCell.clickRightBtnBlcok = ^{
        [self ztHandleButtonsClickLogicWithModel:model];
    };
    
    return ztCell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 200;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZTOrderDetailViewController *ztDetailVC = [ZTOrderDetailViewController new];

    //取出对应的订单详细
    ZTOrderModel *model = self.dataArr[indexPath.row];
    ztDetailVC.orderId = model.orderId;
    [self.navigationController pushViewController:ztDetailVC animated:YES];
}



#pragma mark - 处理按钮点击事件 2019-1-22
- (void)ztHandleButtonsClickLogicWithModel:(ZTOrderModel *)model {

    NSNumber *paymentType = model.paymentType;
    NSNumber *status = model.status;
    
    FDLog(@"1111:%@-%@",paymentType,status);
    
    if ([paymentType isEqualToValue:@(0)] &&
        [status isEqualToNumber:@(0)]
        ) {
        [self ztHandlePayNowModel:model];
    }else if([paymentType isEqualToNumber:@(1)]) {
        if ([status isEqualToNumber:@(0)] ||
            [status isEqualToNumber:@(1)] ||
            [status isEqualToNumber:@(2)] ||
            [status isEqualToNumber:@(3)]) {
            [self ztHandlePayNowModel:model];
        }
    }else if ([status isEqualToNumber:@(5)] ||
              [status isEqualToNumber:@(6)] ||
              [status isEqualToNumber:@(7)] ||
              [status isEqualToNumber:@(8)] ||
              [status isEqualToNumber:@(9)]) {
        
    }else if ([status isEqualToNumber:@(4)]) {
        [self ztHandleEvaluateModel:model];
    }
}


- (void)ztHandleOnceOrder:(NSString *)orderId {
    FDLog(@"再来一单");
    
    WSZaiLaiYiDanViewController *zlydVC = [[WSZaiLaiYiDanViewController alloc] init];
    zlydVC.userOrderId = orderId;
    
    [self.navigationController pushViewController:zlydVC animated:YES];
}


- (void)ztHandleEvaluateModel:(ZTOrderModel *)model {
    FDLog(@"评价");
    EvaluateController *evalateVC = [[EvaluateController alloc] init];
    evalateVC.fdDeliveryType = FDDeliveryTypeZiTi;
    evalateVC.userOrderId = model.orderId;
    
    [self.navigationController pushViewController:evalateVC animated:YES];
}

- (void)ztHandlePayNowModel:(ZTOrderModel *)model {
    FDLog(@"立即支付");
    
    NSNumber *paymentType = model.paymentType;
    NSNumber *status = model.status;
    NSString *orderId = model.orderId;
    
    //一个按钮(在线支付)
    if ([paymentType isEqualToNumber:@(1)]) {
        FDLog(@"3333:%@-%@",paymentType,status);
        if ([status isEqualToNumber:@(1)] ||
            [status isEqualToNumber:@(2)] ||
            [status isEqualToNumber:@(3)]) {
            
            FDLog(@"22222");
            [FDPaytypeAlertTool showAlertOnePayTypeOnlinePayBlock:^{
                [self ztRequestOnlinePayWithOrderId:orderId];
            }];
        }
        
    //两个按钮(线上支付、线下支付)
    }else if ([paymentType isEqualToNumber:@(0)] &&
              [status isEqualToNumber:@(0)]) {
        
        [FDPaytypeAlertTool showAlertTwoPaytypePayOnlineBlock:^{
            [self ztRequestOnlinePayWithOrderId:orderId];
        } offlineBlock:^{
            [self ztRequestOfflinePayWithOrderId:orderId];
        }];
    }
}


- (void)ztRequestOnlinePayWithOrderId:(NSString *)orderId {

    //1-23需要转菊花盖住按钮防止按钮重复点击
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    //点击“在线支付”按钮，调用接口(87号)：/user/order/payment/online
    [FDHttpAPi requestPayOnlineWithOrderId:orderId successBlock:^(id responseObjc) {
        [self.hud hideAnimated:YES];
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            //得到支付“url”连接，展示webview界面，同确认订单部分逻辑
            NSString *url = responseObjc[@"data"][@"url"];
            WSPayUrlViewController *payurlVC = [[WSPayUrlViewController alloc] init];
            payurlVC.payUrl = url;
            [self.navigationController pushViewController:payurlVC animated:YES];
            
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"zt线上支付请求失败:%@",[error localizedDescription]);
        [self.hud hideAnimated:YES];
    }];
}


//点击“线下支付”按钮，调用接口(88号)：/user/order/payment/offline
//接口调用成功后，刷新当前订单列表即可
- (void)ztRequestOfflinePayWithOrderId:(NSString *)orderId {
    [FDHttpAPi requestPayOfflineWithOrderId:orderId successBlock:^(id responseObjc) {
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            [self loadZTData]; //重新请求一次,进行页面刷新
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"线下支付报错:%@",[error localizedDescription]);
    }];
}


#pragma mark - 请求数据
- (void)loadZTData {
    //1：自提订单     status: nil 获取全部订单 
    [FDHttpAPi requestDDOrderListWithDeliveryType:@(1) status:nil successBlock:^(id responseObjc) {
        
        [self.tv1.mj_header endRefreshing];
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            NSArray *data = responseObjc[@"data"];
            //非空才进行模型转换
//            if (data.count == 0) return;
            //清空之前的数据,防止约刷越多
            [self.dataArr removeAllObjects];
            
            for (NSDictionary *dic in data) {
                ZTOrderModel *model = [ZTOrderModel mj_objectWithKeyValues:dic];
                [self.dataArr addObject:model];
            }
            
            //主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.dataArr.count) {
                    self.nodateView.hidden = YES;
                }else {
                    self.nodateView.hidden = NO;
                }
                [self.tv1 reloadData];
            });
            
        }else { //toast
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        [self.tv1.mj_header endRefreshing];
        FDLog(@"发生了错误:%@",[error localizedDescription]);
    }];
}

@end
